package cn.dansj.common.utils.list;

import cn.dansj.common.utils.transfer.Transformation;

import java.util.*;

public class UnmodifiableArrayList<T> extends AbstractList<T> implements RandomAccess {
    private final Object[] elements;
    private final int size;
    private static final Object[] EMPTY_ELEMENT_DATA = {};

    /**
     * The given elements are used directly (a defensive copy is not made),
     * and the given size is used as the size of this list. It is the callers
     * responsibility to make sure the size is accurate.
     *
     * @param elements The elements to use.
     */
    public UnmodifiableArrayList(T[] elements) {
        this.elements = Transformation.requireNonNullElseGet(elements, () -> EMPTY_ELEMENT_DATA);
        this.size = this.elements.length;

    }

    public UnmodifiableArrayList(Collection<? extends T> c) {
        Object[] a = c.toArray();
        if ((size = a.length) != 0) {
            if (c.getClass() == ArrayList.class) {
                elements = a;
            } else {
                elements = Arrays.copyOf(a, size, Object[].class);
            }
        } else {
            elements = EMPTY_ELEMENT_DATA;
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public T get(int index) {
        return (T) elements[index];
    }

    @Override
    public int size() {
        return size;
    }
}